package parser;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Iterator;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.JsonNode;




/**
 *
 * @author Ilio Catallo, Eleonora Ciceri
 * @version: 1.0
 * @see: Parser
 * 
 * Description: The class implements JSON parser
 * 
 * Date: Nov 16, 2011
 */
public class JSONParser extends Parser {
        
    /**
     * Constructor for the class JSONParser
     * @param attributes 
     */
    public JSONParser() {
        super();
    }

    @Override
    public void parse(InputStream document){
        try {
            
            this.responseAttributes.clear();
            
            // Create the JSON Object and navigate trough it
            String jsonTxt = IOUtils.toString(document);
            ObjectMapper mapper = new ObjectMapper();
            JsonNode childNode;
            
            JsonNode node = mapper.readValue(jsonTxt, JsonNode.class);
            
            for (int i = 0; i < this.navigationPath.size(); i++)
                node = node.get(this.navigationPath.get(i));
            
            
         
            for (int i = 0; i < node.size(); i++) {
                
                Iterator keyIterator = this.attributes.keySet().iterator();
                HashMap<String, String> currAttribute = new HashMap<String, String>();
                
                childNode = node.get(i);
                while (keyIterator.hasNext()){
                    
                    String keyName = (String)keyIterator.next();
                    currAttribute.put(keyName, childNode.findValue(keyName).asText());
                    
                }
                
                this.responseAttributes.add(currAttribute);
                
            }
             
        } catch (IOException ex) {
        }
    }
    
}
